﻿using Newtonsoft.Json;
using System.Text.RegularExpressions;

namespace Leo.Common.Json
{
    public class LongToStringConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return typeof(long) == objectType || typeof(long?) == objectType;
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            object value = reader.Value;
            if (value != null && !string.IsNullOrEmpty(value.ToString()))
            {
                if (value.GetType() == typeof(string))
                {
                    string text = value.ToString();
                    if (Regex.IsMatch(text, "^\\d+$"))
                    {
                        return long.Parse(text);
                    }
                    DateTime dateTime;
                    if (DateTime.TryParse(text, out dateTime))
                    {
                        return new DateTimeOffset(dateTime).ToUnixTimeSeconds();
                    }
                }
                return value;
            }
            if (!(objectType == typeof(long?)))
            {
                return 0L;
            }
            return null;
        }


        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            writer.WriteValue((value != null) ? value.ToString() : null);
        }
    }
}
